﻿using System;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using HinduShop.DbClassLib.Mappings;
using NHibernate;
using NHibernate.Cfg;

namespace HinduShop.DbClassLib
{
    public class UnitOfWorkFactory : IUnitOfWorkFactory
    {
        private static ISession currentSession;
        private ISessionFactory sessionFactory;
        private Configuration config;

        public Configuration Configuration
        {
            get { return config; }
        }

        public ISessionFactory SessionFactory
        {
            get
            {
                return (sessionFactory ?? (sessionFactory = Configuration.BuildSessionFactory()));
            }
        }

        private void Configure()
        {
            config = Fluently.Configure().
                Database(
                    MsSqlConfiguration
                        .MsSql2008
                        .ConnectionString(x => x.FromConnectionStringWithKey("ApplicationServices"))
                            .UseReflectionOptimizer()
                            )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ProductMap>())
                .BuildConfiguration();
        }

        public UnitOfWorkFactory()
        {
            Configure();
        }

        public ISession CurrentSession
        {
            get
            {
                if (currentSession == null)
                    throw new InvalidOperationException("U're not in the UOW");
                return currentSession;
            }
            set { currentSession = value; }
        }

        public IUnitOfWork Create()
        {
            ISession session = CreateSession();
            session.FlushMode = FlushMode.Commit;
            currentSession = session;
            return new UnitOfWorkImplementor(session);
        }

        private ISession CreateSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}